package com.example.mobiletest.data

import android.content.Context
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.example.mobiletest.model.BookingData
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.map
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.util.concurrent.TimeUnit

private const val DATA_STORE_NAME = "booking_data_store"
private const val CACHE_KEY = "booking_data"
private const val TIMESTAMP_KEY = "last_update_timestamp"
private const val CACHE_EXPIRY_MINUTES = 5L

class BookingCache(private val context: Context) {

    private val Context.dataStore by preferencesDataStore(DATA_STORE_NAME)

    suspend fun getCachedData(): BookingData? {
        return context.dataStore.data
            .map { preferences ->
                preferences[stringPreferencesKey(CACHE_KEY)]?.let { jsonString ->
                    BookingData.decodeFromString(jsonString)
                }?.apply { isCacheData = true }
            }
            .firstOrNull()
    }

    suspend fun shouldRefreshCache(): Boolean {
        val lastUpdate = context.dataStore.data
            .map { preferences ->
                preferences[longPreferencesKey(TIMESTAMP_KEY)] ?: 0L
            }
            .firstOrNull() ?: 0L
        return System.currentTimeMillis() - lastUpdate > TimeUnit.MINUTES.toMillis(
            CACHE_EXPIRY_MINUTES
        )
    }

    suspend fun saveDataToCache(data: BookingData) {
        context.dataStore.edit { preferences ->
            preferences[stringPreferencesKey(CACHE_KEY)] = Json.encodeToString(data)
            preferences[longPreferencesKey(TIMESTAMP_KEY)] = System.currentTimeMillis()
        }
    }

}